<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: MOZZ
  Date: 2021/12/19
  Time: 14:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<c:set var="user" value="${sessionScope.user}" />
<c:set var="blog" scope="request" value="${requestScope.blog}"/>
<c:if test="${user==null}">
    <c:redirect url="login.jsp" />
</c:if>
<html>

<head>
    <title>Title</title>
    <link rel="stylesheet" href="public/css/add_blog.css">
    <link rel="stylesheet" href="public/css/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="public/css/iconfont.css">
    <link rel="stylesheet" href="public/css/markdown.css">
    <link rel="stylesheet" href="public/css/layout/header.css">

</head>

<body>
    <div class="tar-bar">
        <div class="left-box">
            <div class="menu-item">
                <a href="codeBlog"><span class="iconfont icon-home"></span>首页</a>
            </div>
            <div class="menu-item">
                <a href="timeline.jsp?userId=${user.id}"><span class="iconfont icon-time-line"></span>时间轴</a>
            </div>
            <div class="menu-item">
                <a href="TagsServlet"><span class="iconfont icon-tag"></span>标签</a>
            </div>
            <div class="menu-item">
                <span class="iconfont icon-about"></span> 关于
            </div>
        </div>
        <div class="right-box">
            <div class="menu-item">
                <a href="CategoryServlet?userId=${user.id}"><span class="iconfont icon-folder-open"></span>分类</a>
            </div>
            <c:if test="${user!=null}">
                <div class="menu-item">
                    <!-- <span><a href="UserHomeServlet?userId=${user.id}"><c:out value="${user.nickName}"/></a></span>
                    <div class="avatar-box">
                        <img class="avatar" src="uploads/avatar/${user.avatar}" alt="">
                    </div> -->
                    <a href="UserHomeServlet?userId=${user.id}"><span class="iconfont icon-user"></span>个人中心</a>
                </div>
            </c:if>
            <c:if test="${user==null}">
                <div class="menu-item">
                    <a href="login.jsp"><button class="btn btn-success">登录</button></a>
                </div>
            </c:if>
            <div class="menu-item public-btn">
                <a href="add_blog.jsp"><button class="btn">发表博客</button></a>
            </div>
        </div>
    </div>
    <form action="HandleUpdateBlogServlet" enctype="multipart/form-data" method="post">
        <!-- 详细信息 -->
        <div class="main-box">
            <div class="info-box">
                <div class="form-group">
                    <label>标题</label>
                    <input required class="form-control" type="text" placeholder="请输入标题" name="title" value="${blog.title}">
                    <small class="form-text text-muted">必填项</small>
                </div>
                <div class="custom-file">
                    <input type="file" name="cover" class="custom-file-input" id="customFile">
                    <label class="custom-file-label" for="customFile">选择上传封面（可选）</label>
                </div>
                <div class="add-tag">
                    <button class="btn btn-primary" id="tag-btn" type="button">添加标签</button>
                    <div id="show-tag"></div>
                    <div class="panel tag-panel">
                        <div class="tags"></div>
                        <button class="btn btn-success confirm-btn" onclick="confirmTag()" type="button">确认</button>
                    </div>
                </div>
                <div class="add-category">
                    <button class="btn btn-primary" id="category-btn" type="button">添加分类</button>
                    <div id="show-category"></div>
                    <div class="panel category-panel">
                        <div class="categories"></div>
                        <button class="btn btn-success confirm-btn" onclick="confirmCategory()" type="button">确认</button>
                        <button class="btn btn-primary confirm-btn" id="#confirm-new-category" onclick="showPopupPanel()" type="button">新建分类</button>
                    </div>
                </div>
                <button class="btn btn-success" type="submit">提交</button>
            </div>
            <input type="hidden" name="blogId" value="<c:out value="${blog.id}"/>">
            <!--输入内容  -->
            <div class="editer-box">
                <div class="header">输入內容</div>
                <textarea required id="editer" name="content">${blog.content}</textarea>
            </div>
            <!-- 动态展示内容 -->
            <div class="show-box">
                <div class="header">markdown预览</div>
                <div id="markdown-box">
                </div>
            </div>
        </div>

    </form>
    <!-- 新建分类模态框 -->
    <div id="add-category-panel">
        <div class="pop-panel">
            <form>
                <h4>新建分类</h4>
                <div class="form-group">
                    <label>分类名称</label>
                    <input required id='add-category-name' type="text" class="form-control" placeholder="分类名称" />
                </div>
                <div class="btn-group">
                    <button class="btn btn-success" type="button" id="add-category-btn">添加</button>
                    <button class="btn btn-info" type="button" onclick="showPopupPanel()">取消</button>
                </div>
            </form>
        </div>
    </div>
</body>
<script src="public/js/jquery/jquery.js"></script>
<script>
    // 保存用户信息
    let userId = "${user.id}"

    // 点击添加标签，弹出提示框，使用ajax获取所有标签的数据
    let $tagPanel = $(".tags")
    $("#tag-btn").click(getTags)
    let tagFlag = false

    function getTags() {
        tagFlag = !tagFlag
        if (tagFlag) {
            $(".tag-panel").css("display", "block")
        } else {
            $(".tag-panel").css("display", "none")
            return
        }
        $.ajax({
            url: 'QueryAllTagServlet',
            success: result => {
                $tagPanel.empty();
                result.forEach(item => {
                    let html = '<input class="tag-check" tag="'+item.name+'" type="checkbox" name="tags" value="' + item
                        .id + '">'
                    html += item.name
                    $tagPanel.append(html)
                })
            }
        })
    }

    // 完成选择标签
    function confirmTag() {
        $("#show-tag").empty()
        $('.tag-check').each(function () {
            if(this.checked){
                $("#show-tag").append("<span class='iconfont icon-tag'></span><span style='margin-right:5px;''>"+$(this).attr("tag")+"</span>")
            }
            console.log(this.value, this.checked)
        })
        tagFlag = !tagFlag
        $(".tag-panel").css("display", "none")
    }

    // 点击添加分类，弹出提示框，使用ajax查询该用户的分类
    let $categoryPanel = $(".categories")
    $("#category-btn").click(getCategory)
    let categoryFlag = false

    function getCategory() {
        categoryFlag = !categoryFlag
        if (categoryFlag) {
            $(".category-panel").css("display", "block")
        } else {
            $(".category-panel").css("display", "none")
            return
        }
        $.ajax({
            url: 'QueryAllCategoryServlet',
            data: {
                userId,
                flag:"no"
            },
            success: result => {
                console.log(result)
                $categoryPanel.empty();
                result.forEach(item => {
                    let html ='<input class="category-check" category='+item.categoryName+' type="checkbox" name="category" value="' +item.id + '">'
                    html += item.categoryName
                    $categoryPanel.append(html)
                })
            }
        })
    }

    // 完成选择分类
    function confirmCategory() {
        $("#show-category").empty()
        $('.category-check').each(function () {
            if(this.checked){
                $("#show-category").append("<span class='iconfont icon-folder-open'></span><span style='margin-right:5px;''>"+$(this).attr("category")+"</span>")
            }
            console.log(this.value, this.checked)
        })
        categoryFlag = !categoryFlag
        $(".category-panel").css("display", "none")
    }



    // 弹出新建分类
    let popFlag = false

    function showPopupPanel() {
        popFlag = !popFlag
        if (popFlag) {
            $("#add-category-panel").css("display", "flex")
        } else {
            $("#add-category-panel").css("display", "none")
            return
        }
    }


    // 提交新增分类
    $("#add-category-btn").click(function () {
        let categoryName = $('#add-category-name').val()
        if (categoryName.trim() == '') {
            alert("请输入分类名")
            return
        }
        // 发送请求
        console.log(userId)
        $.ajax({
            type: 'POST',
            url: 'AddCategoryServlet',
            data: {
                categoryName,
                userId
            },
            dataType: "text",
            success: result => {
                if (result == 'success') {
                    $("#add-category-panel").css("display", "none")
                    popFlag = false
                }
            },
            errror: err => {
                alert(err)
            }
        })
    })


    // textarea输入框事件
    $('#editer').bind('input propertychange', function () {
        handleInput();
    });


    // 防抖
    let timer

    function handleInput() {
        clearTimeout(
            timer
        ) // 每次进来的时候都将之前的清除掉，如果还没到一秒的时候就将之前的清除掉，这样就不会触发之前setTimeout绑定的事件， 如果超过一秒，之前的事件就会被触发下次进来的时候同样清除之前的timer
        timer = setTimeout(function () {
            let text = $('#editer').val()
            decodeMarkdown(text)
        }, 1000)
    }

    // 发送异步请求解析markdown
    function decodeMarkdown(resource) {
        // 发送异步请求
        $.ajax({
            url: 'DecodeMarkdownServlet',
            data: {
                resource
            },
            dataType: "text",
            success: result => {
                $("#markdown-box").html(result)
            }
        })
    }
</script>

</html>